package cn.edu.ctbu.dp02.service;

import cn.edu.ctbu.dp02.dao.StudentRepository;
import cn.edu.ctbu.dp02.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.PageRequest;

import java.util.List;
import java.util.Optional;

@Service
public class StudentService {

    @Autowired
    public StudentRepository studentRepository;

    public List<Student> getAll() {

        return studentRepository.findAll();
    }

    public Page<Student> getAll(Pageable pageable) {
        return studentRepository.findAll(pageable);
    }

    public Page<Student> getAll(Example<Student>example, Pageable pageable) {
        return studentRepository.findAll(example, pageable);
    }

    public Student findById(int id) {

        return studentRepository.findById(id).get();
    }

    public Student add(Student student) {

        return studentRepository.save(student);
    }

    public Student update(Student student) {

        return studentRepository.save(student);
    }

    public void delete(Integer id) {

        studentRepository.deleteById(id);
    }


    public Optional<Student> findBySno(String sno) {
        return studentRepository.findAll().stream()
                .filter(student -> sno.equals(student.getSno()))
                .findFirst();
    }

    public void deleteBatch(List<Integer> ids) {
        ids.forEach(studentRepository::deleteById);
    }

    public boolean exists(Integer id) {

        return studentRepository.existsById(id);
    }
}